// pages/post-detail.js
var postData = require('../../data/posts-data.js')
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlaying: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      postDetail: postData.postList[options.postId]
    });

    var collList = wx.getStorageSync("collList");
    var postId = this.data.postDetail.postId;
    var that = this;

    if (collList) {
      var isCollection = collList[postId];
      if (isCollection){
        this.setData({
          isCollection: isCollection
        });
      }
    } else {
      var collList = {};
      collList[postId] = false
      wx.setStorageSync("collList", collList);
    }

    if (app.globalData.g_isPlaying && app.globalData.g_playingId == postId) {
      that.setData({
        isPlaying: true
      })
    }

    wx.onBackgroundAudioPlay(function () {
      app.globalData.g_isPlaying = true;
      if (app.globalData.g_playingId == postId) {
        that.setData({
          isPlaying: true
        })
      }
    })

    wx.onBackgroundAudioPause(function () {
      app.globalData.g_isPlaying = false;
      that.setData({
        isPlaying: false
      })
    })

    wx.onBackgroundAudioStop(function () {
      app.globalData.g_isPlaying = false;
      that.setData({
        isPlaying: false
      })
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onCollection: function (event) {
    var postId = this.data.postDetail.postId;
    var isCollection = this.data.isCollection;
    isCollection = !isCollection;
    // 用来改变图层
    this.setData({
      isCollection: isCollection
    });
    var collList = wx.getStorageSync("collList");
    collList[postId] = isCollection;
    wx.setStorageSync("collList", collList);

    wx.showToast({
      title: isCollection ? "收藏成功" : "取消收藏",
    })
  },

  onShare: function (event) {

  },

  onMusic: function (event) {
    var postId = this.data.postDetail.postId;
    var eventPlaying = this.data.isPlaying;
    var detailData = this.data.postDetail;
    if (eventPlaying) {
      wx.pauseBackgroundAudio();
      app.globalData.g_isPlaying = false;
      app.globalData.g_playingId = -1;
    } else {
      wx.playBackgroundAudio({
        dataUrl: detailData.music.url,
        title: detailData.music.title,
        coverImgUrl: detailData.music.coverImg
      });
      app.globalData.g_isPlaying = true;
      app.globalData.g_playingId = postId;
    }

    eventPlaying = !eventPlaying;
    this.setData({
      isPlaying: eventPlaying
    });
  }

})